<template>
  <div class="content-tree">
    <div
      class="content-title-wrapper"
      v-if="node.title"
      :class="{ highlight: String(node.id) === targetId }"
      :id="
        String(node.id) === targetId
          ? `target-${node.id}`
          : undefined
      "
    >
      <div class="content-title">{{ node.title }}</div>
      <div
        class="edit-button"
        v-if="isEditMode && node.content"
        @click="handleEdit"
      >
        <el-button text>
          <el-icon><Edit /></el-icon>
          <span>编辑</span>
        </el-button>
      </div>
    </div>
    <div
      class="content-body"
      v-if="node.content"
      v-html="formatContent(node.content)"
    ></div>
    <div v-if="node.children && node.children.length" class="content-children">
      <ContentTree
        v-for="child in node.children"
        :key="child.id"
        :node="child"
        :targetId="targetId"
        :isEditMode="isEditMode"
        :path="path"
        @edit="handleEdit"
      />
    </div>
  </div>
  <el-dialog
    v-model="editDialogVisible"
    :title="editForm.title"
    width="80%"
    :close-on-click-modal="false"
    class="edit-dialog"
    @closed="handleDialogClosed"
    :destroy-on-close="true"
    top="5vh"
  >
    <div class="editor-wrapper">
      <Toolbar
        :editor="editorRef"
        :default-config="toolbarConfig"
        :mode="mode"
        class="editor-toolbar"
      />
      <Editor
        :default-config="editorConfig"
        :mode="mode"
        class="editor-content"
        @onCreated="handleEditorCreated"
        @onChange="handleEditorChange"
        @onDestroyed="handleEditorDestroyed"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  defineProps,
  onMounted,
  ref,
  watch,
  nextTick,
  defineEmits,
  shallowRef,
  onBeforeUnmount,
} from "vue";
import { Edit } from "@element-plus/icons-vue";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { ElMessage } from "element-plus";
import type {
  IDomEditor,
  IEditorConfig,
  IToolbarConfig,
} from "@wangeditor/editor";
import { editfragmentContent } from "@/api/knowledge";

interface TreeNode {
  title?: string;
  content?: string;
  children?: TreeNode[];
  id: string;
}

const props = defineProps<{
  node: TreeNode;
  targetId?: string;
  isEditMode?: boolean;
  path?: string;
}>();
console.log(props.path)
const emit = defineEmits<{
  (e: "edit", data: { title: string; content: string; id: string }): void;
  (e: "save", data: { title: string; content: string; id: string }): void;
}>();

// 监听 targetId 变化，当找到目标节点时滚动到该位置
watch(
  () => props.targetId,
  (newId) => {
    if (newId) {
      nextTick(() => {
        const targetElement = document.querySelector(`#target-${newId}`);
        if (targetElement) {
          targetElement.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
        }
      });
    }
  },
  { immediate: true }
);

// 格式化内容的函数
function formatContent(content: string) {
  if (!content) return "";

  // 处理换行符
  let formattedContent = content.replace(/\n/g, "<br>");
  // 处理表格样式
  /*   formattedContent = formattedContent.replace(
    /<table/g, 
    '<table style="border-collapse: collapse; width: 100%; margin: 10px 0;"'
  );
  formattedContent = formattedContent.replace(
    /<th/g, 
    '<th style="border: 1px solid #ddd; padding: 8px; text-align: center; background-color: #f5f5f5;"'
  );
  formattedContent = formattedContent.replace(
    /<td/g, 
    '<td style="border: 1px solid #ddd; padding: 8px; text-align: center;"'
  );
 */
  // 处理图片样式，只添加基础类名
  /*  formattedContent = formattedContent.replace(
    /<img/g,
    '<img class="content-image" loading="lazy"'
  );
  
  return formattedContent; */
  return formattedContent;
}

// 添加 editForm 的定义
const editForm = ref({
  title: "",
  content: "",
  id: "",
});

// 添加 editDialogVisible 的定义
const editDialogVisible = ref(false);

// 编辑器实例
const editorRef = shallowRef<IDomEditor>();

// 修改工具栏配置，只使用基础功能
const toolbarConfig = ref<IToolbarConfig>({
  toolbarKeys: [
    'headerSelect',
    'bold',
    'italic',
    'underline',
    'through',
    '|',
    'fontSize',
    'fontFamily',
    'lineHeight',
    '|',
    'bulletedList',
    'numberedList',
    '|',
    'uploadImage',
    'insertTable',
    '|',
    'undo',
    'redo'
  ]
});

// 修改编辑器配置
const editorConfig = ref<IEditorConfig>({
  placeholder: "请输入内容...",
  autoFocus: false,
  scroll: true,
  readOnly: false,
  maxLength: 1000000,
  MENU_CONF: {
    headerSelect: {
      title: '标题',
      options: [
        { value: 'h1', text: '标题1' },
        { value: 'h2', text: '标题2' },
        { value: 'h3', text: '标题3' },
        { value: 'h4', text: '标题4' },
        { value: 'h5', text: '标题5' },
        { value: 'h6', text: '标题6' },
        { value: 'p', text: '正文' }
      ]
    },
    fontSize: {
      title: '字号',
      options: [
        { value: '12px', text: '12px' },
        { value: '14px', text: '14px' },
        { value: '16px', text: '16px' },
        { value: '18px', text: '18px' },
        { value: '20px', text: '20px' },
        { value: '24px', text: '24px' },
        { value: '28px', text: '28px' },
        { value: '32px', text: '32px' }
      ]
    },
    fontFamily: {
      title: '字体',
      options: [
        { value: '宋体', text: '宋体' },
        { value: '微软雅黑', text: '微软雅黑' },
        { value: 'Arial', text: 'Arial' },
        { value: 'Tahoma', text: 'Tahoma' },
        { value: 'Verdana', text: 'Verdana' }
      ]
    },
    lineHeight: {
      title: '行高',
      options: [
        { value: '1', text: '1' },
        { value: '1.5', text: '1.5' },
        { value: '2', text: '2' },
        { value: '2.5', text: '2.5' },
        { value: '3', text: '3' }
      ]
    },
    uploadImage: {
      server: '/api/upload',
      fieldName: 'file',
      maxFileSize: 10 * 1024 * 1024,
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      customInsert(res: any, insertFn: any) {
        insertFn(res.url)
      },
      onError(file: File, err: any, res: any) {
        console.error(`${file.name} 上传出错`, err, res)
      }
    }
  }
});

// 编辑器模式
const mode = ref("default");

// 修改编辑器创建完成时的回调
const handleEditorCreated = (editor: IDomEditor) => {
  console.log("编辑器创建完成", editor);
  editorRef.value = editor;

  // 设置编辑器的初始内容
  if (editForm.value.content) {
    editor.setHtml(editForm.value.content);
  }

  // 添加编辑器事件监听
  editor.on("change", () => {
    const content = editor.getHtml();
    editForm.value.content = content;
  });
};

// 编辑器内容变化时的回调
const handleEditorChange = (editor: IDomEditor) => {
  console.log("编辑器内容变化", editor.getHtml());
  const content = editor.getHtml();
  editForm.value.content = content;
};

// 编辑器销毁时的回调
const handleEditorDestroyed = (editor: IDomEditor) => {
  console.log("编辑器销毁", editor);
  editorRef.value = null;
};

// 修改 handleEdit 函数
const handleEdit = () => {
  // 设置编辑表单的初始值
  editForm.value = {
    title: props.node.title || "",
    content: props.node.content || "",
    id: props.node.id,
  };

  // 打开编辑弹窗
  editDialogVisible.value = true;

  // 在下一个 tick 中设置编辑器内容
  nextTick(() => {
    if (editorRef.value) {
      editorRef.value.setHtml(editForm.value.content || "");
    }
  });
};

// 修改保存编辑的函数
async function handleSaveEdit() {
  try {
    if (!editorRef.value) {
      ElMessage.error("编辑器未初始化");
      return;
    }

    // 获取编辑器内容
    const content = editorRef.value.getHtml();
    console.log(props.path)
    const res = await editfragmentContent({
      'fragment_path': props.path,
      'uname': "cs564e5e000156",
       'content': content
    });
    if(res.code==200){
      ElMessage.success("保存成功");
      editDialogVisible.value = false;
       // 触发保存事件
    emit("edit", {
      id: editForm.value.id,
      title: editForm.value.title,
      content: content,
    });
    }

  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  }
}

// 修改弹窗关闭处理函数
const handleDialogClosed = () => {
  // 销毁编辑器实例
  if (editorRef.value) {
    editorRef.value.destroy();
    editorRef.value = null;
  }
  // 清空编辑表单
  editForm.value = {
    title: "",
    content: "",
    id: "",
  };
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy();
    editorRef.value = null;
  }
});
</script>

<style scoped>
.content-tree {
  padding: 8px 0;
}

.content-title-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.2s ease;
  margin: 4px 0;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
}

.content-title-wrapper:hover {
  background: #f3f4f6;
  border-color: #d1d5db;
}

.content-title-wrapper.highlight {
  background: #eff6ff;
  color: #1d4ed8;
  border: 1px solid #3b82f6;
  padding: 12px 16px;
  margin: 8px 0;
  border-radius: 6px;
}

.edit-button {
  opacity: 0;
  transition: all 0.2s ease;
  margin-left: 12px;
}

.content-title-wrapper:hover .edit-button {
  opacity: 1;
}

.content-title {
  font-size: 16px;
  font-weight: 500;
  color: #374151;
  margin-right: 16px;
  line-height: 1.4;
}

.content-title-wrapper.highlight .content-title {
  color: #1d4ed8;
  font-weight: 600;
}

.content-body {
  margin: 12px 0 12px 20px;
  color: #4b5563;
  line-height: 1.6;
  font-size: 14px;
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
}

.content-children {
  padding-left: 16px;
  position: relative;
}

.content-children::before {
  content: '';
  position: absolute;
  left: 8px;
  top: 0;
  bottom: 0;
  width: 1px;
  background: #e5e7eb;
}

/* 表格样式 */
:deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 12px 0;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
}

:deep(th) {
  background: #f9fafb;
  color: #374151;
  padding: 8px 12px;
  text-align: center;
  font-weight: 500;
  border-bottom: 1px solid #e5e7eb;
  font-size: 14px;
}

:deep(td) {
  border: 1px solid #f3f4f6;
  padding: 8px 12px;
  text-align: center;
  background: #fff;
}

:deep(tr:hover td) {
  background: #f8fafc;
}

/* 代码块样式 */
:deep(pre) {
  background: #f3f4f6;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 12px;
  margin: 12px 0;
  overflow-x: auto;
  font-size: 13px;
}

:deep(code) {
  background: #f3f4f6;
  padding: 2px 4px;
  border-radius: 2px;
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 13px;
}

/* 编辑按钮样式 */
:deep(.edit-button .el-button) {
  color: #6b7280;
  font-size: 14px;
  padding: 6px 12px;
  height: 32px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
  background: #fff;
}

:deep(.edit-button .el-button:hover) {
  color: #3b82f6;
  border-color: #3b82f6;
  background: #f8fafc;
}
</style>
